import io from 'socket.io-client'
import { useServerUserStore } from '@/stores/modules/user-server'

const userStore = useServerUserStore()

// 创建一个单例模式的Socket.io客户端管理器
class SocketManager {
  constructor() {
    this.socket = null;
    this.initialized = false;
    this.pendingListeners = [];
  }

  // 初始化连接
initialize() {
    if (this.initialized) return this.socket;

    console.log('初始化Socket.io连接...');
    
    this.socket = io('http://127.0.0.1:3000', {
      query: {},
      transports: ['websocket', 'polling'],
      autoConnect: false, // 改为手动连接
      reconnection: true,
      reconnectionAttempts: 5,
      reconnectionDelay: 1000,
    });

    // 添加基本事件监听
    this.socket.on('connect', () => {
     
      
      this.emit('user_login', {
        userId: userStore.userInfo.id,
        socketId: this.socket.id
      })

      // 连接成功后 应用 所有挂起的监听器
      this.applyPendingListeners();
    });

    this.socket.on('disconnect', (reason) => {
      console.log('Socket.io连接断开，原因:', reason);
    });

    this.socket.on('connect_error', (error) => {
      console.error('Socket.io连接错误:', error);
    });

    this.initialized = true;
    return this.socket;
  }

  // 连接到服务器
   connect() {
    if (!this.initialized) {
      this.initialize();
    }
    
    if (!this.socket.connected) {
      this.socket.connect();
    }

    return this.socket;
  }

  // 断开连接
  disconnect() {
    if (this.socket && this.socket.connected) {
      this.socket.disconnect();
    }
  }

  // 添加事件监听器
  on(event, callback) {
    if (!this.initialized || !this.socket.connected) {
      // 如果尚未初始化或连接，将监听器添加到挂起列表
      this.pendingListeners.push({ event, callback });
      return;
    }
    
    this.socket.on(event, callback);
  }

  // 应用所有挂起的监听器
  applyPendingListeners() {
    while (this.pendingListeners.length > 0) {
      const { event, callback } = this.pendingListeners.shift();
      this.socket.on(event, callback);
    }
  }

  // 发送事件到服务器
  emit(event, ...args) {
    if (!this.initialized) {
      this.initialize();
    }
    
    if (!this.socket.connected) {
      this.socket.connect();
    }
    
    this.socket.emit(event, ...args);
  }
  
  // 获取连接状态
  isConnected() {
    return this.socket && this.socket.connected;
  }
}

// 创建Socket管理器的单例
const socketManager = new SocketManager();

export default socketManager;